<template>
  <div class="shared-files-container">
    <div class="files-header">
      <h3>共享文件列表</h3>
      <div class="files-actions">
        <button class="refresh-btn" @click="fetchSharedFiles" :disabled="loading">
          {{ loading ? '加载中...' : '刷新' }}
        </button>
      </div>
    </div>
    
    <div v-if="loading" class="loading-indicator">
      正在加载共享文件列表...
    </div>
    
    <div v-else-if="error" class="error-message">
      {{ error }}
    </div>
    
    <div v-else-if="files.length === 0" class="empty-files">
      当前没有可浏览的共享文件。
    </div>
    
    <div v-else class="files-table-container">
      <table class="files-table">
        <thead>
          <tr>
            <th>文件名</th>
            <th>共享者</th>
            <th>类型</th>
            <th>大小</th>
            <th>共享时间</th>
            <th>访问量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(file, index) in files" :key="file.md5">
            <td >
              <div style="display: flex; align-items: center; gap: 8px;">
                <div class="file-icon" :class="getFileIconClass(getFileExtension(file.file_name))"></div>
                {{ file.file_name }}
              </div>
            </td>
            <td>{{ file.user }}</td>
            <td>{{ file.type === 'null' ? getFileExtension(file.file_name) : file.type }}</td>
            <td>{{ formatFileSize(file.size) }}</td>
            <td>{{ file.create_time }}</td>
            <td>{{ file.pv }}</td>
            <td >
              <button class="action-btn preview-btn" title="预览" @click="previewFile(file)">
                <span>👁️</span>
              </button>
              <button class="action-btn download-btn" title="下载" @click="downloadFile(file)">
                <span>⬇️</span>
              </button>
              <button 
                class="action-btn save-btn" 
                title="转存到我的文件" 
                @click="saveFile(file)"
                v-if="file.user !== currentUser"
                :disabled="savingFiles.has(file.md5)"
              >
                <span>{{ savingFiles.has(file.md5) ? '⏳' : '📥' }}</span>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div class="pagination">
        <span>总计 {{ total }} 个文件</span>
        <div class="pagination-controls">
          <button 
            :disabled="currentPage <= 1"
            @click="changePage(currentPage - 1)"
          >
            上一页
          </button>
          <span>{{ currentPage }} / {{ totalPages }}</span>
          <button 
            :disabled="currentPage >= totalPages"
            @click="changePage(currentPage + 1)"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
    
    <!-- 文件预览对话框 -->
    <FilePreview 
      v-if="showPreview" 
      :show="showPreview" 
      :file="previewingFile" 
      @close="closePreview" 
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import FilePreview from './FilePreview.vue';

// 状态变量
const files = ref([]);
const total = ref(0);
const loading = ref(false);
const error = ref('');
const currentPage = ref(1);
const pageSize = 10; // 每页显示的文件数量

// 文件预览相关状态
const showPreview = ref(false);
const previewingFile = ref(null);

// 转存操作状态
const savingFiles = ref(new Set()); // 使用Set存储正在转存的文件MD5

// 计算总页数
const totalPages = computed(() => {
  return Math.max(1, Math.ceil(total.value / pageSize));
});

// 获取当前用户
const currentUser = computed(() => {
  return localStorage.getItem('user') || '';
});

// 获取文件扩展名
const getFileExtension = (filename) => {
  return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2).toLowerCase();
};

// 获取文件图标类
const getFileIconClass = (fileType) => {
  console.log('fileType:', fileType);
  if (!fileType || fileType === 'null') return 'file-icon';
  
  const typeMap = {
    'png': 'image-icon',
    'jpg': 'image-icon',
    'jpeg': 'image-icon',
    'gif': 'image-icon',
    'mp4': 'video-icon',
    'avi': 'video-icon',
    'mov': 'video-icon',
    'mp3': 'audio-icon',
    'wav': 'audio-icon',
    'pdf': 'pdf-icon',
    'doc': 'doc-icon',
    'docx': 'doc-icon',
    'xls': 'excel-icon',
    'xlsx': 'excel-icon',
    'txt': 'text-icon',
    'zip': 'archive-icon',
    'rar': 'archive-icon',
    'dll': 'binary-icon'
  };
  
  let result = typeMap[fileType.toLowerCase()] || 'file-icon';
  console.log('result:', result);
  return result;
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0 || !bytes) return '0 B';
  
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 获取共享文件列表
const fetchSharedFiles = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    // 从localStorage获取token
    const token = localStorage.getItem('token');
    console.log('获取token:', token); // 添加日志查看token
    
    if (!token) {
      error.value = '用户未登录或登录已过期';
      loading.value = false;
      return;
    }
    
    const start = (currentPage.value - 1) * pageSize;
    
    // 构建请求数据
    const requestData = {
      count: pageSize,
      token: token,
      start: start
    };
    
    console.log('发送共享文件请求:', requestData); // 添加请求数据日志
    
    // 发送请求
    const response = await axios.post('/api/sharefiles?cmd=normal', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    console.log('获取共享文件列表响应:', response.data);
    
    if (response.data.code === 0) {
      files.value = response.data.files || [];
      total.value = response.data.total || 0;
    } else {
      error.value = response.data.message || '获取共享文件列表失败';
      console.error('获取共享文件列表失败:', response.data);
    }
  } catch (err) {
    console.error('获取共享文件列表请求错误:', err);
    error.value = '网络错误，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 切换页码
const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return;
  currentPage.value = page;
  fetchSharedFiles();
};

// 文件操作函数
const previewFile = (file) => {
  // 保存预览文件信息并显示预览对话框
  previewingFile.value = file;
  showPreview.value = true;
};

const closePreview = () => {
  showPreview.value = false;
  setTimeout(() => {
    previewingFile.value = null;
  }, 300); // 等待关闭动画结束后清除文件
};

const downloadFile = async (file) => {
  try {
    // 创建下载链接并执行下载
    const a = document.createElement('a');
    a.href = file.url;
    a.download = file.file_name;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    
    // 下载后更新文件访问计数
    const user = localStorage.getItem('user');
    
    if (!user) {
      console.error('获取用户信息失败，无法更新文件下载计数');
      return;
    }
    
    // 构建请求数据
    const requestData = {
      filename: file.file_name,
      md5: file.md5,
      user: user
    };
    
    console.log('更新文件下载计数请求:', requestData);
    
    // 发送更新计数请求
    const response = await axios.post('/api/dealsharefile?cmd=pv', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    console.log('更新文件下载计数响应:', response.data);
    
    if (response.data.code === 0) {
      // 更新成功，可以选择在本地更新计数
      file.pv = (parseInt(file.pv) || 0) + 1;
    } else {
      console.error('更新文件下载计数失败:', response.data);
    }
  } catch (err) {
    console.error('下载文件或更新计数出错:', err);
  }
};

// 转存共享文件到自己的文件列表
const saveFile = async (file) => {
  try {
    // 获取当前登录用户信息
    const user = localStorage.getItem('user');
    const token = localStorage.getItem('token');
    
    if (!user || !token) {
      showCenterNotification('请先登录后再进行转存操作', 'error');
      return;
    }
    
    // 标记当前文件为正在转存状态
    savingFiles.value.add(file.md5);
    
    // 构建请求数据
    const requestData = {
      filename: file.file_name,
      md5: file.md5,
      user: user,
      token: token
    };
    
    console.log('转存文件请求:', requestData);
    
    // 发送转存请求
    const response = await axios.post('/api/dealsharefile?cmd=save', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    console.log('转存文件响应:', response.data);
    
    // 处理响应结果
    if (response.data.code === 0) {
      showCenterNotification(`文件 "${file.file_name}" 已成功转存到您的文件列表`, 'success');
    } else {
      const errorMsg = response.data.message || '转存文件失败';
      showCenterNotification(errorMsg, 'error');
      console.error('转存文件失败:', response.data);
    }
  } catch (err) {
    console.error('转存文件出错:', err);
    showCenterNotification('转存文件时发生错误，请稍后重试', 'error');
  } finally {
    // 无论成功失败，都移除转存状态
    savingFiles.value.delete(file.md5);
  }
};

// 显示中央通知
const showCenterNotification = (message, type = 'success') => {
  // 创建一个通知元素
  const notificationElement = document.createElement('div');
  notificationElement.className = `center-notification ${type}`;
  
  // 设置内容
  notificationElement.innerHTML = `
    <div class="center-notification-content">
      <span class="center-notification-icon">${type === 'success' ? '✅' : '❌'}</span>
      <span class="center-notification-message">${message}</span>
    </div>
  `;
  
  // 添加到DOM
  document.body.appendChild(notificationElement);
  
  // 添加动画类
  setTimeout(() => {
    notificationElement.classList.add('show');
  }, 10);
  
  // 设置自动消失
  setTimeout(() => {
    notificationElement.classList.remove('show');
    notificationElement.classList.add('hide');
    
    // 动画结束后移除元素
    setTimeout(() => {
      if (document.body.contains(notificationElement)) {
        document.body.removeChild(notificationElement);
      }
    }, 300);
  }, 3000);
};

// 初始加载
onMounted(() => {
  fetchSharedFiles();
});
</script>

<style scoped>
.shared-files-container {
  width: 100%;
  height: 100%;
  overflow: auto;
  position: relative;
}

.files-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.files-header h3 {
  margin: 0;
  font-size: 18px;
}

.files-actions {
  display: flex;
  gap: 10px;
}

.refresh-btn {
  padding: 8px 15px;
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.refresh-btn:hover {
  background-color: #e0e0e0;
}

.refresh-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.loading-indicator,
.error-message,
.empty-files {
  padding: 30px;
  text-align: center;
  color: #666;
  background-color: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #eee;
}

.error-message {
  color: #f44336;
}

.files-table-container {
  width: 100%;
  overflow-x: auto;
}

.files-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.files-table th,
.files-table td {
  text-align: left;
  padding: 10px 10px;
  border-bottom: 1px solid #eee;
}

.files-table th {
  background-color: #f5f5f5;
  font-weight: 500;
  color: #333;
}

.files-table tr:hover {
  background-color: #f9f9f9;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 10px;
  height: 65px;
}

.file-icon {
  width: 20px;
  height: 20px;
  background-color: #ddd;
  border-radius: 2px;
}

.image-icon { background-color: #81c784; }
.video-icon { background-color: #64b5f6; }
.audio-icon { background-color: #9575cd; }
.pdf-icon { background-color: #e57373; }
.doc-icon { background-color: #4fc3f7; }
.excel-icon { background-color: #66bb6a; }
.text-icon { background-color: #9e9e9e; }
.archive-icon { background-color: #ffb74d; }
.binary-icon { background-color: #ba68c8; }
/* .file-icon { background-color: #9e9e9e; } */

.actions-cell {
  display: flex;
  gap: 5px;
  white-space: nowrap;
}

.action-btn {
  padding: 6px;
  background: none;
  border: none;
  cursor: pointer;
  border-radius: 4px;
}

.action-btn:hover {
  background-color: #f0f0f0;
}

.preview-btn {
  color: #2196f3;
}

.download-btn {
  color: #4caf50;
}

.save-btn {
  color: #ff9800;
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-controls button {
  padding: 5px 10px;
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .files-table th:nth-child(2),
  .files-table td:nth-child(2),
  .files-table th:nth-child(3),
  .files-table td:nth-child(3),
  .files-table th:nth-child(5),
  .files-table td:nth-child(5) {
    display: none;
  }
}
</style> 